﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.IO;

namespace HomeBudget
{
    public class CategoryList
    {
        private IList<Category> Categories;
        private string pathToFile;

        public CategoryList(string pathToFile, Category category)
            :this(pathToFile)
        {
            if (category.Name != null)
            {
                AddCategory(category);
            }
            UpdateFile();
        }
        public void Initialize()
        {
            ReadFile();
        }
        public CategoryList(string pathToFile) 
        {
            this.pathToFile = pathToFile;
            Categories = new List<Category>();
        }

        public void AddCategory(Category category)
        {
            ReadFile();
            Categories.Add(category);
            CleanFile();
            UpdateFile();
        }

        public void DeleteCategory(Category category)
        {
            if (Categories.Contains(category))
            {
                Categories.Remove(category);
                UpdateFile();
            }
            else
            {
                MessageBox.Show("There isnt category with that name!");
            }
        }
        private void ReadFile()
        {
            Categories = new List<Category>(2);
            string line;
            StreamReader reader = new StreamReader(this.pathToFile);
            using (reader)
            {
                while ((line = reader.ReadLine()) != null)
                {
                    Categories.Add(new Category(line));
                }
            }
        }
        private void UpdateFile()
        {
            StreamWriter writer = new StreamWriter(this.pathToFile);
            using (writer)
            {
                foreach (var category in Categories)
                {
                    writer.WriteLine(category.Name);
                }
            }
        }
        private void CleanFile()
        {
            File.WriteAllText(this.pathToFile, string.Empty);
        }
        public IList<Category> GetCategories()
        {
            return this.Categories;
        }
        public IList<string> GetCategoriesAsString()
        {
            List<string> strCat = new List<string>();
            foreach (var category in Categories)
            {
                strCat.Add(category.Name);
            }
            return strCat;
        }
    }
}
